import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import type { TaskList, Task } from '@/types/taskList';
import * as taskListApi from '@/api/taskList';
import { saveToLocalStorage } from '@/api/taskList';
import { useCardStore } from '@/store/card';
import type { missionCard } from '@/types/card';
export const useTaskListStore = defineStore('taskList', () => {
    const taskLists = ref<TaskList[]>([]);
    const activeListIndex = ref(0);
    const sidebarCollapsed = ref(false);
    const activeCalendarTaskId = ref<string | null>(null);

    const init = async () => {
        taskLists.value = await taskListApi.getAllTaskLists();
        if (taskLists.value.length === 0) {
            await createTaskList('我的任务');
        } else {
            // 仅修复缺失字段，不强制保存（避免覆盖正常数据）
            taskLists.value.forEach(list => {
                list.tasks.forEach(task => {
                    if (task.completed === undefined) {
                        task.completed = false;
                    }
                });
            });
        }
        // 移除强制保存，仅在数据变更时保存
        // saveTaskListsToLocalStorage();
    };

    const saveTaskListsToLocalStorage = () => {
        localStorage.setItem('taskLists', JSON.stringify(taskLists.value));
    };

    const visibleTaskLists = computed(() =>
        taskLists.value.filter(list => list.visible)
    );

    const activeTaskList = computed(() =>
        taskLists.value[activeListIndex.value]
    );

    const createTaskList = async (name: string) => {
        const newList = await taskListApi.createTaskList(name);
        taskLists.value.push(newList);
        activeListIndex.value = taskLists.value.length - 1;
        return newList;
    };

    const updateTaskListName = async (listId: string, newName: string) => {
        const updatedList = await taskListApi.updateTaskListName(listId, newName);
        const index = taskLists.value.findIndex(list => list.id === listId);
        if (index !== -1 && taskLists.value[index]) {
            taskLists.value[index].name = updatedList.name;
        }
    };

    const toggleTaskListVisibility = async (listId: string, visible: boolean) => {
        const updatedList = await taskListApi.toggleTaskListVisibility(listId, visible);
        const index = taskLists.value.findIndex(list => list.id === listId);
        if (index !== -1 && taskLists.value[index]) {
            taskLists.value[index].visible = updatedList.visible;
        }
    };

    // 同步标志，避免循环同步
    const isSyncingToCalendar = ref(false);

    const addTask = async (listId: string, task: Omit<Task, 'id' | 'createdAt' | 'updatedAt'>, skipCalendarSync: boolean = false) => {
        const newTask = await taskListApi.addTask(listId, task);
        const listIndex = taskLists.value.findIndex(list => list.id === listId);
        if (listIndex !== -1 && taskLists.value[listIndex]) {
            if (!taskLists.value[listIndex].tasks) {
                taskLists.value[listIndex].tasks = [];
            }
            taskLists.value[listIndex].tasks.push(newTask);
            
            // 同步到日历（如果未跳过同步且不在同步中）
            const targetList = taskLists.value[listIndex];
            if (targetList && !skipCalendarSync && !isSyncingToCalendar.value) {
                try {
                    isSyncingToCalendar.value = true;
                    console.log('从任务列表同步到日历 - 添加任务:', newTask.title, newTask.date, '列表:', targetList.name);
                    await syncTaskToCalendar(newTask, 'add', null, listId);
                } catch (syncError) {
                    console.error('同步到日历失败:', syncError);
                    // 不同步失败不影响主流程
                } finally {
                    isSyncingToCalendar.value = false;
                }
            }
        }
    };

    const updateTask = async (listId: string, taskId: string, updates: Partial<Task>, skipCalendarSync: boolean = false) => {
        const listIndex = taskLists.value.findIndex(list => list.id === listId);
        // 保存旧任务信息（用于同步时删除旧卡片）
        let oldTask: Task | null = null;
        if (listIndex !== -1 && taskLists.value[listIndex]?.tasks) {
            const taskIndex = taskLists.value[listIndex].tasks.findIndex(t => t.id === taskId);
            if (taskIndex !== -1 && taskLists.value[listIndex].tasks[taskIndex]) {
                oldTask = { ...taskLists.value[listIndex].tasks[taskIndex] };
            }
        }
        
        const updatedTask = await taskListApi.updateTask(listId, taskId, updates);
        console.log('updateTask: API返回的更新后任务', {
            taskId,
            updates,
            updatedTask: { ...updatedTask }
        });
        
        if (listIndex !== -1 && taskLists.value[listIndex]) {
            if (taskLists.value[listIndex].tasks) {
                const taskIndex = taskLists.value[listIndex].tasks.findIndex(t => t.id === taskId);
                if (taskIndex !== -1 && taskLists.value[listIndex].tasks[taskIndex]) {
                    const oldTask = { ...taskLists.value[listIndex].tasks[taskIndex] };
                    taskLists.value[listIndex].tasks[taskIndex] = {
                        ...taskLists.value[listIndex].tasks[taskIndex],
                        ...updatedTask
                    };
                    console.log('updateTask: 任务状态已更新', {
                        taskId,
                        oldStatus: oldTask.completed,
                        newStatus: taskLists.value[listIndex].tasks[taskIndex].completed,
                        taskIndex
                    });
                    
                    // 同步到日历（如果未跳过同步且不在同步中）
                    const targetList = taskLists.value[listIndex];
                    if (targetList && !skipCalendarSync && !isSyncingToCalendar.value) {
                        try {
                            isSyncingToCalendar.value = true;
                            console.log('从任务列表同步到日历 - 更新任务:', taskLists.value[listIndex].tasks[taskIndex].title, '状态:', taskLists.value[listIndex].tasks[taskIndex].completed, '列表:', targetList.name);
                            await syncTaskToCalendar(taskLists.value[listIndex].tasks[taskIndex], 'update', oldTask, listId);
                        } catch (syncError) {
                            console.error('同步到日历失败:', syncError);
                            // 不同步失败不影响主流程
                        } finally {
                            isSyncingToCalendar.value = false;
                        }
                    }
                }
            }
        }
    };

    const deleteTask = async (listId: string, taskId: string, skipCalendarSync: boolean = false) => {
        // 先获取要删除的任务信息，用于同步删除日历任务
        const listIndex = taskLists.value.findIndex(list => list.id === listId);
        const taskToDelete = listIndex !== -1 && taskLists.value[listIndex]?.tasks
            ? taskLists.value[listIndex].tasks.find(t => t.id === taskId)
            : null;
        
        await taskListApi.deleteTask(listId, taskId);
        if (listIndex !== -1 && taskLists.value[listIndex]) {
            if (taskLists.value[listIndex].tasks) {
                taskLists.value[listIndex].tasks = taskLists.value[listIndex].tasks.filter(
                    task => task.id !== taskId
                );
            }
            
            // 同步删除日历任务（如果未跳过同步且不在同步中）
            const targetList = taskLists.value[listIndex];
            if (targetList && taskToDelete && !skipCalendarSync && !isSyncingToCalendar.value) {
                try {
                    isSyncingToCalendar.value = true;
                    await syncTaskToCalendar(taskToDelete, 'delete', null, listId);
                } catch (syncError) {
                    console.warn('同步删除日历任务失败:', syncError);
                    // 不同步失败不影响主流程
                } finally {
                    isSyncingToCalendar.value = false;
                }
            }
        }
    };

    const moveTaskToEnd = async (listId: string, taskId: string) => {
        const listIndex = taskLists.value.findIndex(list => list.id === listId);
        if (listIndex === -1) return;

        const targetList = taskLists.value[listIndex];
        if (!targetList || !targetList.tasks) return;

        const taskIndex = targetList.tasks.findIndex(t => t.id === taskId);
        if (taskIndex === -1) return;

        const [movedTask] = targetList.tasks.splice(taskIndex, 1);
        if (movedTask) {
            targetList.tasks.push(movedTask);
            targetList.updatedAt = new Date().toISOString();
            await taskListApi.updateTaskListOrder(taskLists.value);
            saveToLocalStorage(taskLists.value);
        }
    };

    const moveTaskToStart = async (listId: string, taskId: string) => {
        const listIndex = taskLists.value.findIndex(list => list.id === listId);
        if (listIndex === -1) return;

        const targetList = taskLists.value[listIndex];
        if (!targetList || !targetList.tasks) return;

        const taskIndex = targetList.tasks.findIndex(t => t.id === taskId);
        if (taskIndex === -1) return;

        const [movedTask] = targetList.tasks.splice(taskIndex, 1);
        if (movedTask) {
            targetList.tasks.unshift(movedTask);
            targetList.updatedAt = new Date().toISOString();
            await taskListApi.updateTaskListOrder(taskLists.value);
            saveToLocalStorage(taskLists.value);
        }
    };

    const setActiveCalendarTaskId = (taskId: string | null) => {
        activeCalendarTaskId.value = taskId;
    };

    const setActiveListIndex = (index: number) => {
        activeListIndex.value = index;
    };

    const toggleSidebar = () => {
        sidebarCollapsed.value = !sidebarCollapsed.value;
    };

    const deleteTaskList = async (listId: string) => {
        await taskListApi.deleteTaskList(listId);
        taskLists.value = taskLists.value.filter(list => list.id !== listId);
    };

    const updateTaskListAnimation = async (listId: string, animationState: 'idle' | 'appearing' | 'disappearing', isTitleVisible: boolean) => {
        const list = taskLists.value.find(l => l.id === listId);
        if (!list) return;
        list.animationState = animationState;
        list.isTitleVisible = isTitleVisible;
        list.updatedAt = new Date().toISOString();
        await taskListApi.updateTaskListAnimation(listId, animationState, isTitleVisible);
    };

    // 同步任务到日历
    const syncTaskToCalendar = async (task: Task, action: 'add' | 'update' | 'delete', oldTask: Task | null = null, taskListId?: string) => {
        const cardStore = useCardStore();
        
        // 确保卡片数据已初始化
        if (cardStore.missionCards.length === 0) {
            await cardStore.initializeCards();
        }
        
        // 将任务日期转换为Date对象
        const taskDateStr = task.date || 'today';
        const taskDate = parseTaskDate(taskDateStr);
        const taskDateFormatted = formatDateForCalendar(taskDate);
        
        if (action === 'add' || action === 'update') {
            let shouldDeleteOldCard = false;
            
            // 如果是更新操作且旧任务信息存在，检查标题、日期或状态是否改变
            if (action === 'update' && oldTask) {
                const oldTaskDateStr = oldTask.date || 'today';
                const oldTaskDate = parseTaskDate(oldTaskDateStr);
                const oldTaskDateFormatted = formatDateForCalendar(oldTaskDate);
                
                // 如果标题或日期改变了，需要先删除旧卡片
                const titleChanged = oldTask.title !== task.title;
                const dateChanged = oldTaskDateFormatted !== taskDateFormatted;
                // 状态改变不需要删除旧卡片，只需要更新即可
                
                if (titleChanged || dateChanged) {
                    shouldDeleteOldCard = true;
                    const normalizedOldTaskTitle = oldTask.title && oldTask.title.trim() ? oldTask.title.trim() : '新任务';
                    
                    // 循环删除所有匹配旧标题/旧日期的卡片
                    let deletedCount = 0;
                    while (true) {
                        const oldCardToDelete = cardStore.missionCards.find(card => {
                            if (taskListId && card.taskListId) {
                                return card.taskListId === taskListId && card.title === normalizedOldTaskTitle;
                            } else {
                                const cardDateStr = formatDateForCalendar(card.date);
                                const normalizedCardTitle = card.title && card.title.trim() && card.title !== '（无标题）' 
                                    ? card.title.trim() 
                                    : '新任务';
                                return cardDateStr === oldTaskDateFormatted && normalizedCardTitle === normalizedOldTaskTitle;
                            }
                        });
                        
                        if (!oldCardToDelete) {
                            break;
                        }
                        
                        console.log('删除旧的任务卡片:', oldCardToDelete.id, normalizedOldTaskTitle);
                        await cardStore.deleteMCard(oldCardToDelete.id, true); // skipTaskListSync = true
                        deletedCount++;
                        
                        if (deletedCount > 10) {
                            console.warn('删除旧卡片时达到最大次数限制，可能存在异常');
                            break;
                        }
                    }
                    
                    if (deletedCount > 0) {
                        console.log(`已删除 ${deletedCount} 张旧的任务卡片（标题或日期已改变）:`, normalizedOldTaskTitle);
                        await new Promise(resolve => setTimeout(resolve, 50));
                    }
                }
            }
            
            // 统一处理空标题：如果标题为空，统一使用"新任务"
            const normalizedTaskTitle = task.title && task.title.trim() ? task.title.trim() : '新任务';
            
            const missionCardData: Omit<missionCard, 'id' | 'createdAt' | 'updatedAt'> = {
                type: 'task',
                date: taskDate,
                title: normalizedTaskTitle,
                missionDate: taskDate,
                remark: task.description || '',
                isFinished: task.completed || false,
                originContext: 'allDay',
                taskListId: taskListId
            };
            
            // 如果删除了旧卡片，直接创建新卡片
            if (shouldDeleteOldCard) {
                console.log('创建新的日历任务卡片（替换旧卡片）:', normalizedTaskTitle, taskDateFormatted);
                await cardStore.saveMCard({
                    ...missionCardData,
                    id: '',
                    createdAt: new Date(),
                    updatedAt: new Date()
                } as missionCard, true); // skipTaskListSync = true
            } else {
                // 如果没有删除旧卡片，说明标题和日期都没变，查找现有卡片进行更新
                const existingCard = cardStore.missionCards.find(card => {
                    if (taskListId && card.taskListId) {
                        return card.taskListId === taskListId && card.title === normalizedTaskTitle;
                    } else {
                        const cardDateStr = formatDateForCalendar(card.date);
                        const normalizedCardTitle = card.title && card.title.trim() && card.title !== '（无标题）' 
                            ? card.title.trim() 
                            : '新任务';
                        return cardDateStr === taskDateFormatted && normalizedCardTitle === normalizedTaskTitle;
                    }
                });
                
                if (existingCard) {
                    // 更新现有卡片
                    console.log('更新日历中的任务卡片:', existingCard.id, normalizedTaskTitle, '状态:', missionCardData.isFinished ? '已完成' : '进行中');
                    const updatedCard = await cardStore.saveMCard({
                        ...missionCardData,
                        id: existingCard.id,
                        createdAt: existingCard.createdAt,
                        updatedAt: new Date()
                    } as missionCard, true); // skipTaskListSync = true
                    console.log('日历任务卡片更新完成:', updatedCard?.id, '新状态:', updatedCard?.isFinished ? '已完成' : '进行中');
                } else {
                    // 找不到现有卡片，创建新卡片
                    console.log('创建新的日历任务卡片:', normalizedTaskTitle, taskDateFormatted);
                    await cardStore.saveMCard({
                        ...missionCardData,
                        id: '',
                        createdAt: new Date(),
                        updatedAt: new Date()
                    } as missionCard, true); // skipTaskListSync = true
                }
            }
        } else if (action === 'delete') {
            // 查找并删除对应的日历任务卡片
            const normalizedTaskTitle = task.title && task.title.trim() ? task.title.trim() : '新任务';
            
            // 优先通过taskListId匹配，如果没有taskListId则通过日期和标题匹配
            const cardToDelete = cardStore.missionCards.find(card => {
                if (taskListId && card.taskListId) {
                    return card.taskListId === taskListId && card.title === normalizedTaskTitle;
                } else {
                    const cardDateStr = formatDateForCalendar(card.date);
                    const normalizedCardTitle = card.title && card.title.trim() && card.title !== '（无标题）' 
                        ? card.title.trim() 
                        : '新任务';
                    return cardDateStr === taskDateFormatted && normalizedCardTitle === normalizedTaskTitle;
                }
            });
            
            if (cardToDelete) {
                console.log('删除日历中的任务卡片:', cardToDelete.id, normalizedTaskTitle);
                await cardStore.deleteMCard(cardToDelete.id, true); // skipTaskListSync = true
            } else {
                console.warn('未找到要删除的日历任务卡片:', normalizedTaskTitle, taskDateFormatted);
            }
        }
    };
    
    // 解析任务日期为Date对象
    const parseTaskDate = (date: string | 'today' | 'tomorrow'): Date => {
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        
        if (date === 'today') {
            return new Date(today);
        } else if (date === 'tomorrow') {
            const tomorrow = new Date(today);
            tomorrow.setDate(tomorrow.getDate() + 1);
            return tomorrow;
        } else {
            // 解析日期字符串 YYYY-MM-DD
            const parts = date.split('-');
            if (parts.length === 3) {
                const year = parseInt(parts[0], 10);
                const month = parseInt(parts[1], 10) - 1; // 月份从0开始
                const day = parseInt(parts[2], 10);
                return new Date(year, month, day);
            }
            return new Date(today); // 默认返回今天
        }
    };
    
    // 格式化日期为字符串（用于比较）
    const formatDateForCalendar = (date: Date): string => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    };

    return {
        taskLists,
        activeListIndex,
        sidebarCollapsed,
        activeCalendarTaskId,
        visibleTaskLists,
        activeTaskList,
        init,
        createTaskList,
        updateTaskListName,
        toggleTaskListVisibility,
        addTask,
        updateTask,
        deleteTask,
        moveTaskToEnd,
        moveTaskToStart,
        setActiveCalendarTaskId,
        setActiveListIndex,
        toggleSidebar,
        deleteTaskList,
        updateTaskListAnimation,
        saveTaskListsToLocalStorage
    };
});
